//
//  SYEmoticonToolBar.swift
//  YANAWeibo
//
//  Created by mac on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum SYEmoticonToolBarButtonType: Int {
    case Normal = 100
    case Emoji = 101
    case Lxh = 102
}

class SYEmoticonToolBar: UIStackView {
    
    // 记录上一次选中的按钮
    var lastSelectedButton: UIButton?
    
    // 定义点击表情按钮的闭包
    var didSelectedEmoticonButtonClosure: ((type: SYEmoticonToolBarButtonType)->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 布局方式
        axis = .Horizontal
        // 填充方式
        distribution = .FillEqually
        
        addChildButton("默认", emImageName: "compose_emotion_table_left", type: .Normal)
        addChildButton("Emoji", emImageName: "compose_emotion_table_mid", type: .Emoji)
        addChildButton("浪小花", emImageName: "compose_emotion_table_right", type: .Lxh)
        
    }
    
    private func addChildButton(title: String, emImageName: String, type: SYEmoticonToolBarButtonType) {
        let button = UIButton()
        button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: .TouchUpInside)
        button.tag = type.rawValue
        button.setTitle(title, forState: .Normal)
        // 设置文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        // 设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        // 设置背景图片
        button.setBackgroundImage(UIImage(named: "\(emImageName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "\(emImageName)_selected"), forState: .Selected)
        // 去掉高亮效果
        button.adjustsImageWhenHighlighted = false
        addArrangedSubview(button)
        // 默认选中状态
        if type == .Normal {
            lastSelectedButton?.selected = false
            button.selected = true
            lastSelectedButton = button
        }
    }
    
    // 监听点击
    @objc private func emoticonButtonClick(btn: UIButton) {
        if btn == lastSelectedButton {
            return
        }
        
        lastSelectedButton?.selected = false
        btn.selected = true
        lastSelectedButton = btn
        
        // 通过tag转换成枚举
        let type = SYEmoticonToolBarButtonType(rawValue: btn.tag)!
        didSelectedEmoticonButtonClosure?(type: type)
    }
    
    // 根据传入的section判断选中哪个按钮
    func selectedEmticonButtonWithSection(section: Int) {
        
        if section + 100 == lastSelectedButton?.tag {
            return
        }
        let button = viewWithTag(section + 100) as! UIButton
        
        lastSelectedButton?.selected = false
        button.selected = true
        lastSelectedButton = button
    }
    

}
